#include "GrappleGun.h"
#include "GrappleHook.h"
#include "MovingObject.h"
#include "../SGD Wrappers/SGD_GraphicsManager.h"
#include "GameplayState.h"
#include "../SGD Wrappers/SGD_AudioManager.h"

GrappleGun::GrappleGun()
{
	SetActive(true);

	m_aFire = SGD::AudioManager::GetInstance()->LoadAudio("resource/audio/Fire.wav");
	m_hImage = SGD::GraphicsManager::GetInstance()->LoadTexture("resource/graphics/Grapple_Gun.png");
}

GrappleGun::GrappleGun(BaseObject* owner)
{
	SetActive(true);
	m_pOwner = owner;
	RegisterForEvent("Kill_Grap");

	m_aFire = SGD::AudioManager::GetInstance()->LoadAudio("resource/audio/Fire.wav");
	m_hImage = SGD::GraphicsManager::GetInstance()->LoadTexture("resource/graphics/Grapple_Gun.png");

}

GrappleGun::~GrappleGun()
{
	UnregisterFromEvent("Kill_Grap");

	KillGrappleHook();

	SGD::AudioManager::GetInstance()->UnloadAudio(m_aFire);
	SGD::GraphicsManager::GetInstance()->UnloadTexture(m_hImage);

}



void GrappleGun::Render()
{
	if (m_bAlive)
		SGD::GraphicsManager::GetInstance()->DrawTexture(
		m_hImage, SGD::Point(m_ptPosition.x - GameplayState::GetInstance()->GetCamX(), m_ptPosition.y - GameplayState::GetInstance()->GetCamY()),
		m_fRotation, m_szSize / 2);


}

void GrappleGun::Update(float elapsedTime)
{
	if (m_pGrappleHook != nullptr)
	{
		m_pGrappleHook->Update(elapsedTime);
		m_fLifeTimer -= elapsedTime;

		if (dynamic_cast<GrappleHook*>(m_pGrappleHook)->GetHasHit())
		{
			oldPosition = newPosition;
			newPosition = m_pOwner->GetPosition();

			if (oldPosition == newPosition)
			{
				m_fDestroyTimer += elapsedTime;
				if (m_fDestroyTimer > .15f)
				{
					m_fDestroyTimer = 0.0f;
					m_fLifeTimer = .5f;
					dynamic_cast<GrappleHook*>(m_pGrappleHook)->ReleaseAll();
					m_pGrappleHook = nullptr;
				}
			}
		}

		if (m_fLifeTimer <= 0.0f && m_pGrappleHook != nullptr)
		{
			m_fLifeTimer = .5f;

			dynamic_cast<GrappleHook*>(m_pGrappleHook)->ReleaseAll();

			m_pGrappleHook = nullptr;
		}

	}
	else
	{
		m_fDestroyTimer = 0.0f;
		m_fLifeTimer = .5f;
	}
}

void GrappleGun::Fire()
{
	if (m_pGrappleHook == nullptr)
	{
		GrappleHook* grapple = new GrappleHook(m_pOwner);

		SGD::AudioManager::GetInstance()->PlayAudio(m_aFire);

		if (!SetGrappleHook(grapple))
			delete grapple;
	}
}

bool GrappleGun::SetGrappleHook(MovingObject* grapple)
{
	if (m_pGrappleHook == nullptr)
	{
		m_fLifeTimer = .5f;
		m_pGrappleHook = grapple;
		m_pGrappleHook->AddRef();
		return true;
	}
	return false;
}

void GrappleGun::KillGrappleHook()
{
	if (m_pGrappleHook != nullptr)
		dynamic_cast<GrappleHook*>(m_pGrappleHook)->ReleaseAll();

	m_pGrappleHook = nullptr;

}

void GrappleGun::HandleEvent(const SGD::Event* pEvent)
{
	KillGrappleHook();
}